<?php

/**
 * 生成密码
 *
 * @param string $password
 * @param string $salt
 * @return string
 */
function generatePasswd($passwd, $salt = '')
{
    return sha1($passwd . $salt);
}

function showError($app, $errMsg = '', $jumpUrl = '', $returnJs = '', $errTitle = 'Error')
{
    include APP_PATH . $app . '/Views/error.php'; 
    exit();
}

function showSucc($app, $succMsg = '', $jumpUrl = '', $returnJs = '', $succTitle = 'Success')
{
    include APP_PATH . $app . '/Views/succ.php'; 
    exit();
}

function redirect($uri = '')
{
    header("Location:" . $uri);
    exit();
}

function startSession()
{
    session_start();
}

function destroySession()
{
    session_destroy();
}

function getSessionData($key)
{
    if (isset($_SESSION['username'])) {
        return $_SESSION[$key];
    } else {
        return null;
    }
}

function setSession($key, $value)
{
    $_SESSION[$key] = $value;
}

function isAjax()
{
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        return true;
    } else {
        return false;
    }
}

function submitHash()
{
    return $_SESSION['submit_hashcode'] = md5(PASSWD_SALT . '-' . time());
}

function isSubmit()
{
    $code = isset($_POST['submit_hashcode']) ? $_POST['submit_hashcode'] : ''; 
    if (empty($code)) {
        return false;
    }
    return getSessionData('submit_hashcode') == $code;
}

function getIp()
{
    if (@$_SERVER['HTTP_CLIENT_IP'] && $_SERVER['HTTP_CLIENT_IP']!='unknown') {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (@$_SERVER['HTTP_X_FORWARDED_FOR'] && $_SERVER['HTTP_X_FORWARDED_FOR']!='unknown') {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return preg_match('/^\d[\d.]+\d$/', $ip) ? $ip : '';
}

function Service($uri, $params = [])
{
    global $serviceSet;
    list($module, $controller, $action) = explode(".", $uri);
    $paths = explode(".", $uri);
    if(empty($paths)) {
        throw new Exception('service path error');
    }
    $action = array_pop($paths);
    $module = implode($paths, "\\");
    $className = sprintf('\\Service\\%sService' , $module);

    if (isset($serviceSet[$uri])) {
        $oController = $serviceSet[$uri];
    } else {
        $oController = new $className();
        if(!method_exists($oController, $action)) {
            throw new \Exception('Action not exists. Controller:' . $controller . ',action:' . $action);
        }
        $serviceSet[$uri] = $oController;
    }

    $apiParams = [];
    $reflectMethod = new \ReflectionMethod($className, $action);
    foreach ($reflectMethod->getParameters() as $param) {
        $name = $param->getName();
        if (isset($params[$name])) {
            $apiParams[$name] = $params[$name];
        } elseif ($param->isOptional()) {
            $apiParams[$name] = $param->getDefaultValue();
        } else {
            throw new \Exception('Missing param:' . $name);
        }
    }
    $result = call_user_func_array(array($oController, $action), $apiParams);
    return $result;
}

